from django.db import models
from django.utils import timezone

# Create your models here.
# app/models.py
from django.db import models

class Department(models.Model):
    name = models.CharField('部门名称', max_length=64)

    class Meta:
        db_table = 'department'
        verbose_name = '部门'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Role(models.Model):
    name = models.CharField('角色名', max_length=64)
    resources = models.ManyToManyField(
        'Resource',
        through='RoleResource',
        related_name='roles',
        verbose_name='拥有资源'
    )

    class Meta:
        db_table = 'role'
        verbose_name = '角色'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Resource(models.Model):
    name = models.CharField('资源名', max_length=64)
    pid = models.ForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        verbose_name='父级资源'
    )
    url = models.CharField('URL', max_length=255, blank=True)

    class Meta:
        db_table = 'resource'
        verbose_name = '资源'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class RoleResource(models.Model):
    role = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name='角色')
    resource = models.ForeignKey(Resource, on_delete=models.CASCADE, verbose_name='资源')

    class Meta:
        db_table = 'role_resource'
        verbose_name = '角色-资源关联'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.role.name} → {self.resource.name}'


class AdminUser(models.Model):
    phone = models.CharField('手机号', max_length=20, unique=True)
    name = models.CharField('姓名', max_length=64)
    password = models.CharField('密码', max_length=128)
    role = models.ForeignKey(Role, on_delete=models.PROTECT, verbose_name='角色')
    department = models.ForeignKey(Department, on_delete=models.PROTECT, verbose_name='部门')
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    updated_at = models.DateTimeField('更新时间', auto_now=True)
    last_login = models.DateTimeField('最后登录时间', null=True, blank=True)
    is_deleted = models.BooleanField('是否删除', default=False)

    class Meta:
        db_table = 'admin_user'
        verbose_name = '后台用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.name} ({self.phone})'


class Workflow(models.Model):
    """工作流模型"""
    id = models.AutoField(primary_key=True)  # 主键自增
    name = models.CharField(max_length=100, unique=True, verbose_name="工作流名称")  # 名称，唯一
    description = models.TextField(null=True, blank=True, verbose_name="工作流描述")  # 描述，可选
    params = models.TextField(verbose_name="参数字段")  # 参数字段，json序列化存储
    status = models.IntegerField(choices=((1, '可用'), (2, '停用')), default=1, verbose_name="状态")  # 状态，1可用 2停用
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "工作流"
        verbose_name_plural = "工作流"
        db_table = "workflow"

    def __str__(self):
        return self.name


class WorkflowPermission(models.Model):
    """工作流权限模型"""
    id = models.AutoField(primary_key=True)  # 主键自增
    role_id = models.ForeignKey(Role, on_delete=models.CASCADE, verbose_name="角色")  # 角色id，外键关联角色表
    workflow_id = models.ForeignKey(Workflow, on_delete=models.CASCADE, verbose_name="工作流")  # 工作流id，外键关联工作流表
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "工作流权限"
        verbose_name_plural = "工作流权限"
        db_table = "workflow_permission"
        unique_together = ('role_id', 'workflow_id')

    def __str__(self):
        return f"{self.role_id.name} - {self.workflow_id.name}"


class Position(models.Model):
    """职位模型"""
    id = models.AutoField(primary_key=True)  # 主键自增
    name = models.CharField(max_length=50, unique=True, verbose_name="职位名称")  # 职位名，唯一
    
    class Meta:
        verbose_name = "职位"
        verbose_name_plural = "职位"
        db_table = "workflow_position"

    def __str__(self):
        return self.name


class WorkflowApprovalNode(models.Model):
    """工作流审批节点配置模型"""
    id = models.AutoField(primary_key=True)  # 主键自增
    workflow_id = models.ForeignKey(Workflow, on_delete=models.CASCADE, verbose_name="工作流")  # 工作流id，外键关联工作流表
    position_id = models.ForeignKey(Position, on_delete=models.CASCADE, verbose_name="职位")  # 职位id，外键关联职位表
    level = models.IntegerField(verbose_name="审批级别")  # 步骤
    type = models.IntegerField(choices=((1, '部门内部'), (2, '公共')), default=1, verbose_name="审批类型")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "工作流审批节点"
        verbose_name_plural = "工作流审批节点"
        db_table = "workflow_approval_node"
        ordering = ['workflow_id', 'level']

    def __str__(self):
        return f"{self.workflow_id.name} - 级别{self.level} - {self.position_id.name}"


class Task(models.Model):
    """任务模型"""
    id = models.AutoField(primary_key=True)  # 主键自增
    name = models.CharField(max_length=100, verbose_name="任务名称")  # 任务名称
    params = models.TextField(verbose_name="表单数据")  # JSON格式存储表单数据
    workflow_id = models.ForeignKey(Workflow, on_delete=models.CASCADE, verbose_name="工作流")  # 工作流id，外键关联工作流表
    userid = models.ForeignKey(AdminUser, on_delete=models.CASCADE, related_name='created_tasks', verbose_name="申请人")
    next_audit = models.ForeignKey(AdminUser, on_delete=models.SET_NULL, null=True, related_name='pending_tasks', verbose_name="下一审批人")
    current_level = models.IntegerField(default=1, verbose_name="当前审批级别")
    task_status = models.IntegerField(choices=((1, '新建'), (2, '审批中'), (3, '已通过'), (4, '已拒绝')), default=1, verbose_name="任务状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "任务"
        verbose_name_plural = "任务"
        db_table = "workflow_task"

    def __str__(self):
        return self.name


class AuditRecord(models.Model):
    """审批记录模型"""
    id = models.AutoField(primary_key=True)  # 主键自增
    task_id = models.ForeignKey(Task, on_delete=models.CASCADE, verbose_name="任务")  # 任务id，外键关联任务表
    audit_user = models.ForeignKey(AdminUser, on_delete=models.CASCADE, verbose_name="审批人")  # 操作人id
    audit_time = models.DateTimeField(auto_now_add=True, verbose_name="审批时间")  # 操作时间，自动添加当前时间
    audit_status = models.IntegerField(choices=((1, '通过'), (2, '拒绝')), verbose_name="审批状态")
    comment = models.TextField(null=True, blank=True, verbose_name="审批意见")
    level = models.IntegerField(verbose_name="审批级别")
    
    class Meta:
        verbose_name = "审批记录"
        verbose_name_plural = "审批记录"
        db_table = "workflow_audit_record"

    def __str__(self):
        return f"{self.task_id.name} - {self.audit_user.name} - {'通过' if self.audit_status == 1 else '拒绝'}"
